<template>
  <div>
    <Card title="模块查询" :bordered="false" :dis-hover="true">
      <div slot="extra">
        <Button
          class="card-extra-item"
          size="small"
          type="primary"
          icon="ios-search"
          @click="search"
          >查询</Button
        >
      </div>
      <Form
        inline
        label-position="right"
        :label-width="100"
        :model="searchParams"
      >
        <Row>
          <Col span="6">
            <FormItem label="所属项目" style="width: 100%">
              <Select
                v-model="searchParams.project"
                clearable
                filterable
                @on-select="getModuleTreeData"
                @on-clear="clearProject"
              >
                <Option
                  v-for="item in projects"
                  :value="item.id"
                  :key="item.id"
                  >{{ item.name }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="模块名称" style="width: 100%">
              <Input
                clearable
                placeholder="请输入模块名称"
                v-model="searchParams.name"
              />
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Card>
    <Card title="模块列表" :bordered="false" :dis-hover="true">
      <div slot="extra">
        <Button
          class="card-extra-item"
          size="small"
          type="primary"
          @click="showDrawer = !showDrawer"
          >{{ showDrawer ? "收起创建模块" : "展开创建模块" }}</Button
        >
        <Button
          class="card-extra-item"
          size="small"
          type="primary"
          @click="showModuleSelectTreeModal"
          >模块搬家</Button
        >
      </div>
      <Table
        :columns="moduleColumns"
        :data="moduleData"
        border
        size="small"
        :tooltip-max-width="500"
        @on-selection-change="selectionChange"
      >
        <template slot-scope="{ row }" slot="project">
          {{ row.project.name }}
        </template>
        <template slot-scope="{ row }" slot="modifier">
          {{ row.modifier.real_name }}
        </template>
        <template slot-scope="{ row }" slot="action">
          <div v-if="!row.is_system">
            <Button
              size="small"
              type="text"
              style="color: #2d8cf0"
              @click="showEditModuleModal(row)"
              >编辑
            </Button>
            <Poptip
              title="确定要删除吗?"
              :confirm="true"
              :transfer="true"
              @on-ok="handleDeleteModule(row.id)"
            >
              <Button size="small" type="text" style="color: #ed4014"
                >删除</Button
              >
            </Poptip>
          </div>
        </template>
      </Table>
      <Page
        transfer
        :total="page.total"
        :current="page.current"
        :page-size="page.pageSize"
        :page-size-opts="page.pageSizeOpts"
        size="small"
        show-elevator
        show-sizer
        show-total
        prev-text="上一页"
        next-text="下一页"
        style="margin-top: 15px"
        @on-change="change"
        @on-page-size-change="pageSizeChange"
      />
    </Card>
    <ModuleCreate
      :createModule.sync="createModule"
      :projectId.sync="projectId"
      :parentModule.sync="parentModule"
      @initModuleTable="initModuleTable"
      @formatModuleTreeData="formatModuleTreeData"
    />
    <ModuleEdit
      :editModule.sync="editModule"
      :module="module"
      @initModuleTable="initModuleTable"
      @formatModuleTreeData="formatModuleTreeData"
    />
    <Drawer
      title="创建模块"
      :scrollable="true"
      :closable="true"
      v-model="showDrawer"
      :mask="false"
      placement="left"
      width="256"
      draggable
    >
      <Select
        v-model="searchParams.project"
        placeholder="请选择项目"
        clearable
        filterable
        prefix="ios-search"
        @on-select="getModuleTreeData"
        @on-clear="clearProject"
      >
        <Option
          v-for="item in projects"
          :value="item.id"
          :key="item.id"
          :label="item.name"
          :tag="item.name"
        />
      </Select>
      <Divider />
      <Button
        type="primary"
        size="small"
        long
        v-if="searchParams.project"
        @click="showCreateModuleModal"
        >创建根模块</Button
      >
      <Tree
        :data="moduleTreeData"
        @on-select-change="getSelectedNodes"
        empty-text="请先选择项目"
      ></Tree>
    </Drawer>
    <Modal
      title="请选择模块的家"
      :closable="false"
      :mask-closable="false"
      :width="600"
      v-model="showModuleSelectTree"
      @on-ok="handleMoveModuleSubmit"
      @on-cancel="handleMoveModuleCancel"
    >
      <div style="height: 230px">
        <SelectTree
          v-model="targetParentModule"
          :treeData="moduleSelectTreeData"
        >
        </SelectTree>
      </div>
    </Modal>
  </div>
</template>

<script>
import { treeToArray } from "@/libs/custom.utils";
import { getProjectNames } from "@/api/HttpAutoTestService/project";
import {
  getModules,
  getModuleNames,
  deleteModule,
  moveModule,
} from "@/api/HttpAutoTestService/module";
import ModuleCreate from "@/view/components/HttpAutoTestService/module/module-create";
import ModuleEdit from "@/view/components/HttpAutoTestService/module/module-edit";
import SelectTree from "_c/select-tree";

export default {
  name: "module",
  components: {
    ModuleCreate,
    ModuleEdit,
    SelectTree,
  },
  mounted() {
    this.search();
  },
  data() {
    return {
      showModuleSelectTree: false,
      showDrawer: false,
      createModule: false,
      editModule: false,
      enableMoveModule: false,
      searchParams: {
        id: [],
        project: "",
        name: "",
      },
      projects: [],
      projectId: "",
      parentModule: "",
      module: {},
      moduleColumns: [
        {
          type: "selection",
          width: 60,
          align: "center",
          fixed: "left",
        },
        {
          title: "模块名称",
          key: "name",
          width: 350,
          tooltip: true,
        },
        {
          title: "所属项目",
          slot: "project",
          width: 350,
          ellipsis: true,
        },
        {
          title: "备注",
          key: "remark",
          minWidth: 350,
          tooltip: true,
        },
        {
          title: "最近维护人",
          slot: "modifier",
          align: "center",
          width: 120,
        },
        {
          title: "操作",
          slot: "action",
          width: 125,
          align: "center",
          fixed: "right",
        },
      ],
      selectedModules: [],
      targetParentModule: "",
      modules: [],
      moduleData: [],
      moduleTreeData: [],
      moduleSelectTreeData: [],
      page: {
        current: 1,
        total: 0,
        pageSize: 50,
        pageSizeOpts: [10, 30, 50, 100, 200],
      },
    };
  },
  methods: {
    search(page) {
      let data = {
        id: this.searchParams.id.toString(),
        project: this.searchParams.project,
        name: this.searchParams.name,
        page: 1,
        page_size: this.page.pageSize,
      };
      if (typeof page == "number") {
        data.page = page;
      }
      this.page.current = data.page;

      getModules(data)
        .then((res) => {
          this.enableMoveModule = this.searchParams.project ? true : false;
          const data = res.data;
          this.moduleData = data.results.map((item) => {
            item["_disabled"] = item.is_system;
            return item;
          });
          this.page.total = data.count;
          if (data.next === null) {
            this.page.current = Math.ceil(this.page.total / this.page.pageSize);
          }
          if (data.previous === null) {
            this.page.current = 1;
          }
        })
        .catch((err) => {
          this.$Modal.error({
            title: "系统异常，请联系管理员……",
            content: JSON.stringify(err),
            closable: true,
          });
        });
    },
    initModuleTable() {
      this.searchParams.id = [];
      this.search();
    },
    getProjectNames() {
      getProjectNames()
        .then((res) => {
          this.projects = res.data;
        })
        .catch((err) => {
          this.$Modal.error({
            title: "系统异常，请联系管理员……",
            content: JSON.stringify(err),
            closable: true,
          });
        });
    },
    showCreateModuleModal() {
      this.projectId = this.searchParams.project;
      this.createModule = true;
    },
    showEditModuleModal(row) {
      let data = {
        project: row.project ? row.project.id : "",
      };
      let { id, name, parent, remark } = row;
      Object.assign(data, { id, name, parent, remark });
      this.module = data;
      this.editModule = true;
    },
    handleDeleteModule(id) {
      deleteModule(id)
        .then((res) => {
          const status = res.status;
          if (status === 204) {
            this.$Message.info("删除成功");
            // 更新模块树
            this.formatModuleTreeData();
            // 删除成功后，将被删除模块的id从searchParams.id列表中删除
            this.searchParams.id = this.searchParams.id.filter((item) => {
              return item !== id;
            });
            this.search();
          }
        })
        .catch((err) => {
          this.$Modal.error({
            title: "系统异常，请联系管理员……",
            content: JSON.stringify(err),
            closable: true,
          });
        });
    },
    getModuleTreeData(val) {
      let project = val.value;
      this.searchParams.project = project;
      this.formatModuleTreeData();
      this.searchParams.id = [];
      this.search();
    },
    formatModuleTreeData() {
      if (this.searchParams.project) {
        getModuleNames({ project: this.searchParams.project }).then((res) => {
          let data = res.data;
          this.modules = data;
          data = data.map((item) => {
            return {
              id: item.id,
              title: item.name,
              parent: item.parent,
              expand: true,
              is_system: item.is_system,
              floor: item.floor,
              project: item.project,
              remark: item.remark,
              render: (h, { root, node, data }) => {
                return h(
                  "div",
                  {
                    style: {
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      width: "100%",
                    },
                  },
                  [
                    h(
                      "span",
                      {
                        style: {
                          overflow: "hidden",
                          whiteSpace: "nowrap",
                        },
                      },
                      data.title
                    ),
                    h("span", {}, [
                      h(
                        "tooltip",
                        {
                          props: {
                            content: "创建子模块",
                            transfer: true,
                          },
                        },
                        [
                          h("Button", {
                            props: {
                              icon: "md-add",
                              type: "text",
                              size: "small",
                            },
                            style: {
                              color: "#2d8cf0",
                              display:
                                !data.is_system && data.floor !== 4
                                  ? "inline"
                                  : "none",
                            },
                            on: {
                              click: () => {
                                if (!data.is_system && data.floor !== 4) {
                                  this.parentModule = data.id;
                                  this.showCreateModuleModal();
                                }
                              },
                            },
                          }),
                        ]
                      ),
                      h(
                        "tooltip",
                        {
                          props: {
                            content: "编辑模块",
                            transfer: true,
                          },
                        },
                        [
                          h("Button", {
                            props: {
                              icon: "md-create",
                              type: "text",
                              size: "small",
                            },
                            style: {
                              color: "#2d8cf0",
                              display: !data.is_system ? "inline" : "none",
                            },
                            on: {
                              click: () => {
                                if (!data.is_system) {
                                  let tempModule = {
                                    project: data.project ? data.project : "",
                                    id: data.id,
                                    name: data.title,
                                    parent: data.parent,
                                    remark: data.remark,
                                  };
                                  this.module = tempModule;
                                  this.editModule = true;
                                }
                              },
                            },
                          }),
                        ]
                      ),
                      h(
                        "tooltip",
                        {
                          props: {
                            content: "删除模块",
                            transfer: true,
                          },
                        },
                        [
                          h("Button", {
                            props: {
                              icon: "md-remove",
                              type: "text",
                              size: "small",
                            },
                            style: {
                              color: "#ed4014",
                              display: !data.is_system ? "inline" : "none",
                            },
                            on: {
                              click: () => {
                                if (!data.is_system) {
                                  this.handleDeleteModule(data.id);
                                }
                              },
                            },
                          }),
                        ]
                      ),
                    ]),
                  ]
                );
              },
            };
          });
          let arrayToTree = require("array-to-tree");
          this.moduleTreeData = arrayToTree(data, {
            parentProperty: "parent",
            childrenProperty: "children",
            customID: "id",
          });
        });
      }
    },
    clearProject() {
      this.searchParams.project = "";
      this.searchParams.id = [];
      this.modules = [];
      this.moduleTreeData = [];
      this.moduleSelectTreeData = [];
      this.search();
    },
    getSelectedNodes(val) {
      const result = treeToArray(val);
      this.searchParams.id = result.map((item) => {
        return item.id;
      });
      this.search();
    },
    selectionChange(val) {
      this.selectedModules = val.map((item) => {
        return item.id;
      });
    },
    showModuleSelectTreeModal() {
      if (this.selectedModules.length > 0) {
        if (this.enableMoveModule) {
          let data = this.modules.map((item) => {
            let tempData = {
              value: item.id,
              title: item.name,
              parent: item.parent,
              expand: true,
            };
            if (this.selectedModules.indexOf(item.id) !== -1) {
              tempData["disabled"] = true;
            }
            return tempData;
          });
          let arrayToTree = require("array-to-tree");
          this.moduleSelectTreeData = arrayToTree(data, {
            parentProperty: "parent",
            childrenProperty: "children",
            customID: "value",
          });
          this.showModuleSelectTree = true;
        } else {
          this.$Message.info(
            "待搬家的模块，必须是【所属项目】查询条件的查询结果"
          );
        }
      } else {
        this.$Message.info("请选择需要搬家的模块");
      }
    },
    handleMoveModuleSubmit() {
      let data = {
        parent: this.targetParentModule,
        modules: this.selectedModules,
      };
      moveModule(data).then((res) => {
        if (res.status === 200) {
          let data = res.data;
          if (data.status === "success") {
            this.$Message.info(data.msg);
            // 刷新左侧树结构
            this.formatModuleTreeData();
          } else if (data.status === "fail") {
            this.$Message.error(data.msg);
          }
          this.handleMoveModuleCancel();
        } else {
          this.$Message.error("模块搬家失败");
        }
      });
    },
    handleMoveModuleCancel() {
      this.showModuleSelectTree = false;
      this.selectedModules = [];
      this.targetParentModule = "";
      this.moduleSelectTreeData = [];
      this.search();
    },
    change(val) {
      this.page.current = val;
      this.search(val);
    },
    pageSizeChange(val) {
      this.page.pageSize = val;
      this.search();
    },
  },
};
</script>

<style>
.ivu-tree-title {
  width: 100%;
}
</style>
